
const utils = require('../../utils/util.js');
const common = require('../../utils/common.js');

Component({
  properties: {
    // 显示-隐藏
    show: {
      type: Boolean,
      value: false,
    },
    // 货号
    productNo: {
      type: String,
      value: "C13611051",
    },

    // 物料分类
    mateCateMeta: {
      type: Object,
      value: [],
    },
    // 物料分类-tree
    mateCateTree: {
      type: Object,
      value: [],
    },
    // 物料颜色tree
    mateColorTree: {
      type: Object,
      value: [],
    },
    // 版单数据
    plateTasts: {
      type: Array,
      value: [],
    }
    //      mateCateMeta="{{materialCategoryMeta}}"
    //  mateCateTree="{{materialCategoryTree}}"

  },
  attached() {
    // 组件实例进入页面节点树时执行
    console.log('Properties:', this.properties);
  },
  ready() {
    // 组件布局完成后执行
    console.log('Properties after layout:', this.properties);
  },
  pageLifetimes: {
    show: function () {
      // 页面被展示
      console.log("页面被展示")
    },
    hide: function () {
      // 页面被隐藏
      console.log("页面被隐藏")
    },
    resize: function (size) {
      // 页面尺寸变化
      console.log("页面尺寸变化")
    }
  },
  lifetimes: {
    attached: function () {
      // 在组件实例进入页面节点树时执行
      console.log("在组件实例进入页面节点树时执行")
      this.initBomForm()
      // this.plaTaskSelList()
      // this.plaTaskSelList()
      // *** 损耗选项 ***
      let lossTree = [] // 
      let lossTreeData = [] // 损耗选项
      // 从 0 到 25 
      for (let li = 0; li < 26; li++) {
        lossTreeData.push({
          "name": li + "%",
          "value": li,
        })
        lossTree.push(li + "%")
      }
      this.setData({
        lossTree: lossTree,
        lossTreeData: lossTreeData,
      });
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
      console.log("在组件实例被从页面节点树移除时执行")
    },
  },
  data: {
    // 临时数据
    // bom选择
    bomSelList: [], // { "orderCode": "面料" }, { "orderCode": "辅料" }
    bomSelIdx: "", //   index  

    // 物料类型
    abmMateItemTypes: [{ "name": "面料", "value": "01" }, { "name": "辅料", "value": "02" }, { "name": "包装辅料", "value": "03" }, { "name": "配料", "value": "04" }], //  物料项目类型 01面料 02辅料 03耗材 04里料',
    abmMateItemTypeIdx: "", //  物料项目类型 index  
    abmMateCateIdxArr: [
        0,0
    ], // 分类tree-选择的ID
    // 损耗
    lossTreeData: [], // 损耗tree-data
    lossTree: [], // 损耗tree
    selectStrArr: {
      loss: '', // 损耗名称
      mateItemType: '', // 物料项目类型
      mateColorName: '', // 选择的颜色名称 
      bomSelStr: '', // 选择的bom名称 
      materielName: '' // 物料名称
    },

    // 表格数据
    bomFrom: {
      attritionRate: '', // 损耗
      materialCategoryNode: '', // 品类
      materialClassificationText: '', // 品类名称
      materialColor: '', // 物料颜色
      materialName: '', // 物料名称
      materialCode: '',
      materialSupplierSkuId: '', // 供应链面料id
      mateItemType: '', // 物料项目类型名称
      materialTtemType: '', // 物料项目类型
      pieceDosage: '',
      orderCode: '', // 版单号
      isLookingMaterial: false,
    },
    showMaterialInquiry: false,
    showCategory: false,
    showColorPicker: false,
    categoryList: [], // 品类数据
  },
  methods: {
    setDataIndex: function (e) {
        let { field } = e.currentTarget.dataset;
        let value = e.detail.value;
        if (!value) {
          this.setData({
            'bomFrom.materialSupplierSkuId': '',
            'bomFrom.materialCode': '',
          })
        }
        this.setData({
          [field]: value,
        });
      },
    onClose: function () {
      console.log("关闭按钮")
      this.initBomForm() // 重置
      this.triggerEvent('handleGetPlateTasts',false)
      this.setData({ show: false });
    },

    // bom下拉选择
    plaTaskSelList: function () {
      // todo 待发布，就改下请求方法

      // 调试模式
    // common.request_api_test(
    //  "http://127.0.0.1:9091/sgsPdmPlateTask/plateSelectListByProdNo?productNo="+this.properties.productNo,
    // 生产模式
    // common.request_api(
    //   "/api/ums/sgsPdmPlateTask/plateSelectListByProdNo?productNo="+this.properties.productNo,


      common.request_api_test(
        "http://127.0.0.1:9091/sgsPdmPlateTask/plateSelectListByProdNo?productNo="+this.properties.productNo,
        {},
        false
      ).then(res => {
        console.log("bom下拉选择-res", res) 
        this.setData({
          bomSelList: res.data, // 选择的值  
        });

      });

    },
    // fomr初始化
    initBomForm:function(e){
      let iBomFrom = {
        orderCode: '',
        materialTtemType: '', // 类型 
        materialName: '',
        materialColor: '',
        pieceDosage: '', // 用量
        attritionRate: 0,
      }
     let selectStrArr =  {
        loss: '', // 损耗名称
        mateItemType: '', // 物料项目类型
        mateColorName: '', // 选择的颜色名称 
        bomSelStr: '', // 选择的bom名称 
        materielName: '' // 物料名称
      }
      this.setData({
        selectStrArr: selectStrArr,
        bomFrom: iBomFrom, // 选择的值  
      });
      
      // this.setData({ show: false });
     
    },
    // bom选择 **********
    bomBindChange: function (e) {
      let index = e.detail.value
      // this.setData({
      //   bomSelIdx: index, // 选择的值 
      //   ["selectStrArr.bomSelStr"]: this.data.bomSelList[index].mainPlateOrderNo,// 选中的标题
      //   ["bomFrom.orderCode"]: this.data.bomSelList[index].orderCode // 选中的值

      // });
      this.setData({
        'bomFrom.orderCode': this.data.plateTasts[index].orderCode
      })
    },

    // 类型 *********
    abmCgMateGroup: function (e) {
      let index = e.detail.value
      this.setData({
        abmMateItemTypeIdx: index, // 选择的值 
        ["selectStrArr.mateItemType"]: this.data.abmMateItemTypes[index].name, // 选中的标题
        ["bomFrom.materialTtemType"]: this.data.abmMateItemTypes[index].value
      });
    },


    // 分类 *********

    // 保存bom-选择物料分类
    abmCgMateCate(e) {
      let mateCateTree = this.properties.mateCateTree;
      console.log("选择物料分类:mateCateTree", mateCateTree)

        console.log(e.detail.value,'e.detail.value');
      const info = this.getCombinedInfo(mateCateTree, e.detail.value)
      console.log(info);

      this.setData({
        'bomFrom.materialCategoryNode': info.infoId.join(','),
        'bomFrom.materialClassificationText': info.infoName.join('/'),
        abmMateCateIdxArr: e.detail.value, // 选择的值 
        // ["abmFormData.mateCate"]: mateCateMeta, // todo 分类
      });

    },
    getCombinedInfo(arr,indices){
      let current = arr;
      let infoId = [];
      let infoName = [];
      for (let index of indices) {
          current = current[index];
          infoId.push(current.value)
          infoName.push(current.name)
          if (Array.isArray(current.children)) {
              current = current.children;
          }
      }
      return {
        infoId,
        infoName
      }
    },
    // 保存bom-分类列改变
    abmColCgMateCate(e) {
      // abmFormData.mateCate
      let mateCateTree = this.properties.mateCateTree;
      console.log("添加bom:mateCateTree", mateCateTree)
      let abmMateCateIdxArr = this.data.abmMateCateIdxArr;
      let index = e.detail.value;
      let column = e.detail.column;
      if (column == 0) {
        abmMateCateIdxArr = [index, 0];
      }
      if (column == 1) {
        abmMateCateIdxArr[1] = index;
      }
      // 重新获取tree 分级数组 [{"name":"一级"}],[{"name":"二级"}]  
      let mateCateMeta = utils.opAefMetaCateMeta(
        abmMateCateIdxArr,
        mateCateTree
      );
      this.setData({
        abmMateCateIdxArr, // 选中的
        mateCateMeta, // 选中的 
      });

    },

    // 输入 
    inputChange (e) {
      let { field } = e.currentTarget.dataset
      let { value } = e.detail
      if (field == 'price' || field == 'single_piece') {
        const regex = /^[0-9]*(\.[0-9]*)?$/;
        value = value.replace(/[^0-9.]/g, '');
      }
      this.setData({
        [`bomFrom.${field}`]: value
      })
      console.log(this.data.bomFrom)
    },

    // 保存bom-损耗
    abmCgLoss: function (e) {
      console.log("损耗")
      let index = e.detail.value
      this.setData({
        ["bomFrom.attritionRate"]: this.data.lossTreeData[index].value, // 选中的值
        ["selectStrArr.loss"]: this.data.lossTreeData[index].name,// 选中的标题 
      });
    },
    // 选择颜色
    colorBindChange: function (e) {
      let index = e.detail.value
      console.log("选择颜色", this.properties.mateColorTree)
      this.setData({
        ["bomFrom.materialColor"]: this.properties.mateColorTree[index].name, // 选中的值
        ["selectStrArr.mateColorName"]: this.properties.mateColorTree[index].label, // 选中的值

      });
    },
    handleColorChange(event) {
      const list = event.detail
      this.setData({
        ["bomFrom.materialColor"]: list[0].label, // 选中的值
        ["selectStrArr.mateColorName"]: list[0].label, // 选中的值
      });
    },
    // saveBom 
    saveBom: function (e) {
      let that = this
      let bomFrom = that.data.bomFrom
      console.log("saveBom-that.data.bomFrom", bomFrom)
      if (bomFrom.orderCode == '') {
        wx.showToast({
          title: '请选择Bom',
          icon: 'error',
          duration: 2000,
        });
        return false;
      }
      if (bomFrom.materialTtemType === '') {
        wx.showToast({
          title: '请选择物料类型',
          icon: 'error',
          duration: 2000,
        });
        return false;
      }

      if (bomFrom.materialName == '') {
        wx.showToast({
          title: '物料名称不能为空',
          icon: 'error',
          duration: 2000,
        });
        return false;
      }
      if (bomFrom.materialColor == '') {
        wx.showToast({
          title: '请选择物料颜色',
          icon: 'error',
          duration: 2000,
        });
        return false;
      }

      if (bomFrom.pieceDosage == '') {
        wx.showToast({
          title: '单件用量不能为空',
          icon: 'error',
          duration: 2000,
        });
        return false;
      }

      if (bomFrom.attritionRate == undefined || bomFrom.attritionRate === '') {
        wx.showToast({
          title: '请选择损耗',
          icon: 'error',
          duration: 2000,
        });
        return false;
      }
    
      if(this.data.abmMateCateIdxArr.length != 2){
        wx.showToast({
            title: '请选择物料品类',
            icon: 'error',
            duration: 2000,
          });
          return false;
      }

      let abmMateCateIdxArr = this.data.abmMateCateIdxArr
      let mateCateTree = this.properties.mateCateTree
      let item1 = mateCateTree[abmMateCateIdxArr[0]]
      let item2 = mateCateTree[abmMateCateIdxArr[0]].children[abmMateCateIdxArr[1]]
      let name1 = item1.name
      let name2 = item2.name
      let value1 = item1.value
      let value2 = item2.value
      bomFrom.materialCategoryNode = value1+","+value2
      bomFrom.materialCategoryLastNode = value2
      bomFrom.materialClassificationText = name1+"/"+name2

      // orderCode: '',
      // materialTtemType: '',
      // materialName: '',
      // materialColor: '',
      // pieceDosage: '', // 用量
      // attritionRate: 0,

      // 调试模式
      // common.request_api_test(
      //  'http://127.0.0.1:9091/sgsPdmPlateTask/saveBomItem',
      // 生产模式
      // common.request_api(
      //   "/api/ums/sgsPdmPlateTask/saveBomItem",

      common.request_api(
        '/api/pdm/sgsPdmPlateTask/saveBomItem',
        bomFrom,
        false
      ).then(res => {
        console.log("bom下拉选择-res", res)
        wx.showToast({
          title: res.msg,
          icon: 'success',
          duration: 2000,
        });
        // 清空数据
        this.setData({
          show: false
        })
        this.initBomForm()
        this.triggerEvent('handleGetPlateTasts',true)
        // 关闭窗口
      }).catch(error => {
        console.error("error:", error);
        wx.showToast({
          title: '提交错误',
          icon: 'error',
          duration: 2000,
        });
      })

      // var result = app.request_api ('admin/Template/mini_save_bom', data, true, 'POST', {}, true);
      // result.then (res => {
      //     wx.showToast ({
      //         title: res.msg,
      //         icon: 'success',
      //         duration: 2000,
      //     });
      //     this.onClickHide ();
      //     this.get_template_detail ()
      // }) 
    },

    // onHideAddBom: function (e) { 
    //   console.log("onHideAddBom-隐藏-添加bom窗口")
    //   this.setData({  
    //       create_bom_show: false, 
    //   })
    // },
    // 显示绑定物料
    handlemMateriel() {
      console.log(1221);
      this.setData({
        showMaterialInquiry: true
      })
    },
    handleColor() {
      this.setData({
        showColorPicker: true
      })
    },
    handleSelect(event) {
      const row = event.detail.row
      let bomFrom = this.data.bomFrom
      bomFrom = {
        ...bomFrom,
        materialColor: row.materialColor,
        materialName: row.materialName,
        materialCode: row.materialCode,
        materialCategoryNode: row.materialCategoryNode,
        materialClassificationText: row.materialClassificationText,
        materialSupplierSkuId: row.supplierSkuCode
      }
      this.setData({
        bomFrom
      })
    },
    handleClose() {
      this.setData({
        'bomFrom.materialSupplierSkuId': '',
        'bomFrom.materialCode': '',
      })
    },
    newHandleClose(e) {
      const name = e.target.dataset.name
      this.setData({
        [name]: false
      })
    },
    openMaterialPopup() {
      this.selectComponent('.material-popup').openPopup();
    },
    handlePopupClose() {
      console.log('弹框已关闭');
    }
  }
})